package com.ldx.java_chatroom.service;

import com.ldx.java_chatroom.mapper.MessageMapper;
import com.ldx.java_chatroom.mapper.MessageSessionMapper;
import com.ldx.java_chatroom.model.MessageSession;
import com.ldx.java_chatroom.model.item.MessageSessionUserItem;
import com.ldx.java_chatroom.model.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MessageSessionService {
    @Resource
    MessageSessionMapper mapper;
    @Resource
    MessageMapper messageMapper;
    public Object getSessionList(HttpSession session) {
        ArrayList<MessageSession> lists = new ArrayList<>();
        if(session == null){
            log.error("session为null");
            return lists;
        }
        User user = (User) session.getAttribute("User");
        if(user == null){
            log.error("用户未登录");
            return lists;
        }
        List<Integer> sessionIdLists = mapper.getSessionIdByUserId(user.getUserId());
        for(Integer id : sessionIdLists){
           MessageSession messageSession = new MessageSession();
           messageSession.setFriends(mapper.getFriendListBySessionId(id, user.getUserId()));
           messageSession.setSessionId(id);
           String lastMessage = messageMapper.getLastMessageBySessionId(id);
           if(lastMessage == null){
               messageSession.setLastMessage("");
           }else {
               messageSession.setLastMessage(lastMessage);
           }
           //messageSession.setLastMessage("我喜欢你");

           lists.add(messageSession);
        }
        return lists;
    }
    //添加数据三项必须同时完成 因此使用事务这个注释
    @Transactional
    public Object addMessageSession(int toUserId, User user) {
        MessageSession messageSession = new MessageSession();
        mapper.addMessageSession(messageSession);

        //添加会话发起者
        MessageSessionUserItem item1 = new MessageSessionUserItem();
        item1.setSessionId(messageSession.getSessionId());
        item1.setUserId(user.getUserId());
        mapper.addMessageSessionUser(item1);

        //添加toFriend
        MessageSessionUserItem item2 = new MessageSessionUserItem();
        item2.setUserId(toUserId);
        item2.setSessionId(messageSession.getSessionId());
        mapper.addMessageSessionUser(item2);

        log.info("添加会话成功 sessionId = "+messageSession.getSessionId()+"userId = " +user.getUserId()+"friendId ="+toUserId);
        return messageSession.getSessionId();
    }
}
